/**
 * 
 */
package com.explgo.backend.rest;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.explgo.backend.service.GenericException;

/**
 * The super class of rest service controllers.
 * 
 * @author Jialiang(Cain) Wang
 *
 */
public class AbstractController {
	@Autowired
	private MessageSource messageSource;
	
	@ExceptionHandler({GenericException.class})
	public void handleErrors(Throwable throwable, HttpServletRequest request, HttpServletResponse response) {
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		response.setContentType("application/json");
		
		try {
			GenericException exception = (GenericException) throwable;
			
			Locale locale = RequestContextUtils.getLocale(request);
			String message = exception.getMessage();
			message = messageSource.getMessage(message, exception.getArguments(), message, locale);
			
			ControllerError error = new ControllerError();
			error.setMessage(message);
			ControllerErrorResponse errorResponse = new ControllerErrorResponse();
			errorResponse.setError(error);
			
			new ObjectMapper().writeValue(response.getWriter(), errorResponse);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
